﻿using DongFangGuoKai.TaskPlatform.Commn.ApiModule;
using DongFangGuoKai.TaskPlatform.Commn.ApiModule.Dto;
using DongFangGuoKai.TaskPlatform.Commn.Attributes;
using DongFangGuoKai.TaskPlatform.Commn.ConfigureOptions;
using DongFangGuoKai.TaskPlatform.Commn.LogModule;
using DongFangGuoKai.TaskPlatform.Domain;
using DongFangGuoKai.TaskPlatform.Job.OutRoundIssuance.Dto;
using DongFangGuoKai.TaskPlatform.Job.OutRoundIssuance.Model;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Quartz;
using RestSharp;
using SqlSugar;

namespace DongFangGuoKai.TaskPlatform.Job.OutRoundIssuance
{
    [Job("出库任务", "出库下发", "出库下发任务3分钟执行一次")]
    public class OutRoundIssuanceJob : IJob
    {
        public IApiClient _apiClient { get; set; }
        public IOptions<UrlConfigOption> _urlOption { get; set; }
        public ISqlSugarClient _client { get; set; }
        public LogHelper<OutRoundIssuanceJob> _log { get; set; }

        public SyncIDType _syncID = SyncIDType.OutRoundIn;
        static int TaskCount = 0;
        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                if (TaskCount >= 10)
                {
                    var info = JobHelper.GetJobInfo<OutRoundIssuanceJob>();
                    //停止Job
                    //await JobHelper.StopJob(context, info.Item1, info.Item2);

                    //重置0
                    TaskCount = 0;

                    _log.LogCtmError("[错误信息：任务异常次数超过10次，Job已终止]");

                    //发送邮箱
                    var logRes = _client.Queryable<Nlog>().Where(x => x.Message.Contains("出库下发"))
                        .Where(x => x.Level == "Error")
                        .OrderByDescending(x => x.Id)
                        .Take(11).ToList();
                    JobHelper.SendEmail(logRes, info.Item1, info.Item2);

                    return;
                }

                UrlConfigOption? urlConfigOption = _urlOption.Value;
                string url = Path.Combine(urlConfigOption.HaiNingUrl, JobHelper.GetHHSuffixUrl(_syncID));
                string id = JobHelper.GetSyncLastId(_syncID);
                Parameter[] getPara = null;
                var syncTsk = await _client.Queryable<SyncTaskIEntity>().FirstAsync(x => x.Id == id);
                if (syncTsk != null)
                {
                    getPara = new Parameter[1]
                       {
                        new QueryParameter("id",syncTsk.TaskID.ToString())
                       };
                }
                var res = _apiClient.Get<ApiResultData>(url, getPara);
                if (res.Code != "200")
                {
                    TaskCount++;
                    _log.LogError(url, getPara?.ToString(), res.Msg, res.Code);
                    await Task.CompletedTask;
                    return;
                }
                if (!res.Data.Any())
                {
                    await Task.CompletedTask;
                    return;
                }
                var data = res.Data.ToObject<OutRoundIssuanceModel>();
                var dataPickingId = data.PickingId;
                OutRoundIssuanceDto outRoundIssuanceDto = new OutRoundIssuanceDto()
                {
                    OrderSn = data.PickingNumber,
                    WhId = data.StoreId,
                    WhName = data.StoreName,
                    NeedDeptName = data.NeedDeptName
                };
                if (data.Items != null && data.Items.Count > 0)
                {
                    outRoundIssuanceDto.ShippingOrderDetailPlusLockCellDTOs = new();
                    foreach (var item in data.Items)
                    {
                        outRoundIssuanceDto.ShippingOrderDetailPlusLockCellDTOs.Add(
                            new OutRoundIssuanceDetailDto
                            {
                                Batch = item.Batch,
                                MaterialCode = item.MaterialCode,
                                MaterialName = item.MaterialName,
                                MaterialNorms = item.MaterialNorms,
                                MaterialNum = item.PickingCount,
                                MaterialId = item.PickingId, //关联单Id    
                                PickingItemId = item.PickingItemId,
                                CellCode = item.StoreLocationId
                            });
                    }
                }
                string postUrl = Path.Combine(urlConfigOption.WMSUrl, JobHelper.GetWMSSuffixUrl(_syncID));
                var postRes = _apiClient.Post<ApiDataResult<bool>>(postUrl, outRoundIssuanceDto);

                if (postRes.Code != 200)
                {
                    TaskCount++;
                    _log.LogError(postUrl, JsonConvert.SerializeObject(outRoundIssuanceDto), postRes.Msg, postRes.Code.ToString());
                    await Task.CompletedTask;
                    return;
                }
                if (syncTsk == null)
                {
                    _client.Insertable(new SyncTaskIEntity()
                    {

                        Id = id,
                        TaskID = dataPickingId,
                        CreateTime = DateTime.Now


                    }).ExecuteCommand();
                }
                else
                {
                    syncTsk.TaskID = dataPickingId;
                    syncTsk.ModiflyTime = DateTime.Now;
                    _client.Updateable(syncTsk).UpdateColumns("TaskID", "ModiflyTime").ExecuteCommand();
                }
                _log.LogSuc(postUrl, JsonConvert.SerializeObject(outRoundIssuanceDto));
            }
            catch (Exception ex)
            {
                TaskCount++;
                _log.LogCtmError(ex.Message);
            }

            await Task.CompletedTask;
        }
    }
}
